#!/bin/sh
get_default_cr(){
  local CRD="$1"
  shift 1

  local CR_NAME
  CR_NAME="$(kubectl get "$CRD" -n "$OPERATOR_NAMESPACE" -o json)"
  CR_NAME="$(printf '%s' "$CR_NAME" \
    | jq -r ".items[]|select(.metadata.annotations[\"stackgres.io/operatorVersion\"] == \"$STACKGRES_VERSION\")|.metadata.name")"
  CR_NAME="$(printf '%s' "$CR_NAME" \
    | head -n 1)"

  kubectl get "$CRD" -n "$OPERATOR_NAMESPACE" "$CR_NAME" "$@"
}

get_default_cr_filter(){
  local CRD="$1"
  local FILTER="$2"
  shift 2

  local CR_NAME
  CR_NAME="$(kubectl get "$CRD" -n "$OPERATOR_NAMESPACE" -o json)"
  CR_NAME="$(printf '%s' "$CR_NAME" \
    | jq -r ".items[]|select(.metadata.annotations[\"stackgres.io/operatorVersion\"] == \"$STACKGRES_VERSION\")|.metadata.name")"
  CR_NAME="$(printf '%s' "$CR_NAME" \
    | grep "$FILTER")"
  CR_NAME="$(printf '%s' "$CR_NAME" \
    | head -n 1)"

  kubectl get "$CRD" -n "$OPERATOR_NAMESPACE" "$CR_NAME" "$@"
}

get_default_pgconfig(){
  local FILTER="$1"
  shift 1
  get_default_cr_filter "sgpgconfigs.stackgres.io" "$FILTER" "$@"
}


get_default_conn_pool(){
  get_default_cr "sgpoolconfigs.stackgres" "$@"
}

get_default_backupconf(){
  get_default_cr "sgbackupconfigs.stackgres.io" "$@"
}

get_default_profile(){
  get_default_cr "sginstanceprofiles.stackgres.io" "$@"
}

get_generated_cr(){
  local NAMESPACE="${CLUSTER_NAMESPACE:-$OPERATOR_NAMESPACE}"
  local CRD="$1"
  shift 1

  local CR_NAME
  CR_NAME="$(kubectl get "$CRD" -n "$NAMESPACE" -o jsonpath='{.items[*].metadata.name}')"
  kubectl get "$CRD" -n "$OPERATOR_NAMESPACE" "$CR_NAME" "$@"
}

get_generated_pgconfig(){
  get_generated_cr "sgpgconfigs.stackgres.io" "$@"
}

get_generated_conn_pool(){
  get_generated_cr "sgpoolconfigs.stackgres" "$@"
}

get_generated_backupconf(){
  get_generated_cr "sgbackupconfigs.stackgres.io" "$@"
}

get_generated_pgconfig(){
  get_generated_cr "sgpgconfigs.stackgres.io" "$@"
}

get_generated_profile(){
  get_generated_cr "sginstanceprofiles.stackgres.io" "$@"
}